package com.hue.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hue.service.OSSService;
import com.hue.utils.OSSConfig;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;

@Service
public class OSSServiceImpl implements OSSService {
    //上传文件
    @Override
    public String upload(MultipartFile file) throws Exception {
        String endpoint = OSSConfig.END_POINT;
        String accessKeyId = OSSConfig.KEY_ID;
        String accessKeySecret = OSSConfig.KEY_SECRET;
        String bucketName = OSSConfig.BUCKET_NAME;

        // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream is = file.getInputStream();
        //修改文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename.split("[.]")[0];
        //文件名加上时间戳
        fileName += System.currentTimeMillis();
        //获取文件类型
        String suffix = originalFilename.split("[.]")[1];
        if(!"jpg".equalsIgnoreCase(suffix) &&
            !"png".equalsIgnoreCase(suffix) &&
            !"jpeg".equalsIgnoreCase(suffix)){
            throw new Exception("不支持的文件类型");
        }

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String date = new DateTime().toString("yyyy/MM/dd");
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, "head_photo/"+date+"/"+fileName+"."+suffix, is);

        // 关闭OSSClient。
        ossClient.shutdown();

        //返回访问的url
        //https://edu-glxy-01.oss-cn-beijing.aliyuncs.com/test/SpringMVC%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0.doc
        String url = "https://edu-glxy-01.oss-cn-beijing.aliyuncs.com/head_photo/"+date+"/"+fileName+"."+suffix;
        return url;
    }
}
